package com.shuyou;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;

import com.shuyou.net.Data;
import com.shuyou.net.JsonParser;
import com.shuyou.net.ServerInfo;
import com.shuyou.net.StaticHttpClient;
import com.shuyou.net.UserInfo;
import com.shuyou.values.Values;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity implements OnClickListener{

	private static final String TAG = "RegisterActivity";
	
	private Intent i;
	private String uid;
	private String sex;
	private String nickname;
	private String sessionid;
	private String platform_kind;
	private Map<String, String> map;
	
	private ServerInfo si = null;
	
	private TextView textNickName = null;
	private TextView textSex = null;
	private TextView textPhoneNum = null;
	private TextView textQQ = null;
	private TextView textWechat = null;
	
	private EditText editNickName = null;
	private EditText editPhoneNum = null;
	private EditText editQQ       = null;
	private EditText editWechat   = null;
	private RadioButton boy = null;
	private RadioButton girl = null;
	
	private ProgressBar registerProgress = null;
	private Dialog dialogUsrInfo = null;
	
	private RelativeLayout dialogNotice = null;
	private Dialog noticeDialog = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register);
		findViewById(R.id.register_usrlogo).setOnClickListener(this);
		findViewById(R.id.register_nickname).setOnClickListener(this);
		findViewById(R.id.register_sex).setOnClickListener(this);
		findViewById(R.id.register_age).setOnClickListener(this);
		findViewById(R.id.register_phonenum).setOnClickListener(this);
		findViewById(R.id.register_qq).setOnClickListener(this);
		findViewById(R.id.register_wechat).setOnClickListener(this);
		findViewById(R.id.register_confirm_button).setOnClickListener(this);
		
		registerProgress = (ProgressBar)findViewById(R.id.register_progress);
		dialogNotice = (RelativeLayout)getLayoutInflater()
						.inflate(R.layout.shuyou_dialog_userinfo_notice, null);
		
		noticeDialog = new Dialog(this, R.style.ShuyouDialog);
		noticeDialog.setContentView(dialogNotice);
		noticeDialog.show();
		noticeDialog.setCanceledOnTouchOutside(true);
		
		InitDisplay();
	}
	
	/**
	 * 根据获得的第三方数据，初始化显示
	 */
	private void InitDisplay(){
		textNickName = (TextView)findViewById(R.id.register_con_nickname);
		textSex = (TextView)findViewById(R.id.register_con_sex);
		textPhoneNum = (TextView)findViewById(R.id.register_con_phonenum);
		textQQ = (TextView)findViewById(R.id.register_con_qq);
		textWechat = (TextView)findViewById(R.id.register_con_wechat);
		
		i = getIntent();
		uid = i.getStringExtra("uid");
		sex = i.getStringExtra("sex");
		nickname = i.getStringExtra("nickname");
		sessionid = i.getStringExtra("sessionid");
		platform_kind = i.getStringExtra("platform_kind");
		textNickName.setText(nickname);
		if(sex.equals("1"))
		{
			textSex.setText(Values.MALE);
		}
		else
		{
			textSex.setText(Values.FEMALE);
		}
		
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
			case R.id.register_usrlogo: 
				showInfoDialog(R.layout.shuyou_dialog_userinfo_logo, 1);
				break;
			case R.id.register_nickname: 
				showInfoDialog(R.layout.shuyou_dialog_userinfo_nickname, 2);
				
				break;
			case R.id.register_sex: 
				showInfoDialog(R.layout.shuyou_dialog_userinfo_sex, 3);
				break;
			case R.id.register_age: 
				//showInfoDialog(R.layout.shuyou_dialog_register_age, 4);
				break;
			case R.id.register_phonenum: 
				showInfoDialog(R.layout.shuyou_dialog_userinfo_phonenum, 5);
				break;
			case R.id.register_qq: 
				showInfoDialog(R.layout.shuyou_dialog_userinfo_qq, 6);
				break;
			case R.id.register_wechat: 
				showInfoDialog(R.layout.shuyou_dialog_userinfo_wechat, 7);
				break;
			case R.id.dialog_nickname_confirm_button:
				textNickName.setText(editNickName.getText().toString());
				dialogUsrInfo.dismiss();
				break;
			case R.id.dialog_sex_confirm_button:
				if(boy.isChecked()){
					textSex.setText(Values.MALE);
				}
				else{
					textSex.setText(Values.FEMALE);
				}
				dialogUsrInfo.dismiss();
				break;
			case R.id.dialog_phonenum_confirm_button:
				String tmpPhoneNum = editPhoneNum.getText().toString();
				/*检测电话号码的正确性*/
				Pattern p = Pattern.compile
						("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
				Matcher m = p.matcher(tmpPhoneNum);
				if(m.matches()) {
					textPhoneNum.setText(tmpPhoneNum);
					dialogUsrInfo.dismiss();
				}
				else {
					final TextView tmpTv = (TextView)dialogUsrInfo.findViewById(R.id.dialog_phonenum_title);
					tmpTv.setText("号码有误");
					tmpTv.setTextColor(getResources().getColor(R.color.red));
					new Handler().postDelayed(new Runnable() {

			            @Override
			            public void run() {
			             tmpTv.setText(getResources().getString(R.string.phonenum_setting));
			             tmpTv.setTextColor(getResources().getColor(R.color.dialog_text));
			            }
			        }, 1000);     //1秒后修改回来
				}
				break;
			case R.id.dialog_qq_confirm_button:
				textQQ.setText(editQQ.getText().toString());
				dialogUsrInfo.dismiss();
				break;
			case R.id.dialog_wechat_confirm_button:
				textWechat.setText(editWechat.getText().toString());
				dialogUsrInfo.dismiss();
				break;
				
			case R.id.register_confirm_button:
				if(textPhoneNum.getText().equals("") && textQQ.getText().equals("")
						&& textWechat.getText().equals("")) {   //三个联系方式至少填写一个
					noticeDialog.show();
				}
				else {
					registerProgress.setVisibility(View.VISIBLE);
					String nick_name = textNickName.getText().toString();
					String sex = textSex.getText().toString();
					String tel = textPhoneNum.getText().toString();
					String QQ = textQQ.getText().toString();
					String mic_msg = textWechat.getText().toString();
					UserInfo.nickName = nick_name;
					UserInfo.sex      = sex;
					UserInfo.phoneNum = tel;
					UserInfo.QQ       = QQ;
					UserInfo.weChat   = mic_msg;
					System.out.println(nick_name + ":" + sex + ":" + tel + ":" + QQ
							+ ":" + mic_msg + ":" + sessionid + ":" + uid + ":" + platform_kind);
					sendPersonalInfo(nick_name, sex, tel, QQ, mic_msg, sessionid,
							uid, platform_kind);
				}
				break;
			default: break;
		}
	}
	
	/**
	 * 根据id弹出相应窗口
	 * @param id
	 */
	private void showInfoDialog(int id, int whichInfo){
		LinearLayout dialogUsrInfoView = (LinearLayout)getLayoutInflater()
				.inflate(id, null);
		dialogUsrInfo = new Dialog(this, R.style.ShuyouDialog);
		dialogUsrInfo.setContentView(dialogUsrInfoView);
		dialogUsrInfo.show();
		dialogUsrInfo.setCanceledOnTouchOutside(true);
		switch(whichInfo){
			case 1: break;
			case 2:
				editNickName = (EditText)dialogUsrInfo.findViewById(R.id.dialog_nickname_setting);
				editNickName.setText(textNickName.getText().toString());
				dialogUsrInfo.findViewById(R.id.dialog_nickname_confirm_button).setOnClickListener(this);
				break;
			case 3:
				boy = (RadioButton)dialogUsrInfo.findViewById(R.id.dialog_userinfo_sex_boy);
				girl = (RadioButton)dialogUsrInfo.findViewById(R.id.dialog_userinfo_sex_girl);
				
				if(textSex.getText().toString() == Values.FEMALE){
					girl.setChecked(true);
				}
				else{
					boy.setChecked(true);
				}
				dialogUsrInfo.findViewById(R.id.dialog_sex_confirm_button).setOnClickListener(this);
				break;
			case 4:
				//地点选择保留
				break;
			case 5:
				editPhoneNum = (EditText)dialogUsrInfo.findViewById(R.id.dialog_phonenum_setting);
				editPhoneNum.setText(textPhoneNum.getText().toString());
				dialogUsrInfo.findViewById(R.id.dialog_phonenum_confirm_button).setOnClickListener(this);
				break;
			case 6:
				editQQ = (EditText)dialogUsrInfo.findViewById(R.id.dialog_qq_setting);
				editQQ.setText(textQQ.getText().toString());
				dialogUsrInfo.findViewById(R.id.dialog_qq_confirm_button).setOnClickListener(this);
				break;
			case 7:
				editWechat = (EditText)dialogUsrInfo.findViewById(R.id.dialog_wechat_setting);
				editWechat.setText(textWechat.getText().toString());
				dialogUsrInfo.findViewById(R.id.dialog_wechat_confirm_button).setOnClickListener(this);
				break;
			default:
				break;	
		}
	}
	
	/**
	 * 向服务器发送个人信息
	 * @param nick_name
	 * @param sex
	 * @param tel
	 * @param QQ
	 * @param mic_msg
	 * @param sessionid
	 * @param platform_userid
	 * @param platform_kind
	 */
	private void sendPersonalInfo(String nick_name, String sex, String tel,
			String QQ, String mic_msg, String sessionid,
			String platform_userid, String platform_kind) {
		map = new HashMap<String, String>();
		
		map.put("nick_name", nick_name);
		map.put("sex", sex);
		map.put("tel", tel);
		map.put("QQ", QQ);
		map.put("mic_msg", mic_msg);
		map.put("sessionid", sessionid);
		// map.put("location", "");
		map.put("is_update", "0");
		map.put("platform_userid", platform_userid);
		map.put("platform_kind", platform_kind);
		
		new Thread() {

			@Override
			public void run() {
				try {
					String strResult = StaticHttpClient.doPost(
							Values.PERSONAL_INFO_URL, map);
					if (strResult == null) {
						Log.i(TAG, "strResult = null");
					} else {
						Log.i(TAG, strResult);
					}
					si = (ServerInfo) JsonParser.parseObject(strResult,
							ServerInfo.class);// 需要处理空指针异常
					if(si == null) {
						Log.i(TAG, "si = null");
						Message msg = new Message();
						msg.what = Values.NETWORK_ERROR;
						handler.sendMessage(msg);
					} else {
						System.out.println(si);
						String status = si.getStatus();
						if (status.equals("10001")) {
							//操作失败
							Message message = new Message();
							message.what = Values.FAIL_TO_REGISTER;
							message.obj = "操作失败";
							handler.sendMessage(message);
						} else if (status.equals("10002")) {
							//参数错误
							Message message = new Message();
							message.what = Values.FAIL_TO_REGISTER;
							message.obj = "参数错误";
							handler.sendMessage(message);
						} else if(status.equals("10000")) {
							//操作成功进入首页						
							Message message = new Message();
							message.what = Values.SUCCESS_TO_REGISTER;
							message.obj = si.getData();
							handler.sendMessage(message);
						} else {
							Message message = new Message();
							message.what = Values.FAIL_TO_REGISTER;
							message.obj = "未知错误";
							handler.sendMessage(message);
						}
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					Message msg = new Message();
					msg.what = Values.NETWORK_ERROR;
					handler.sendMessage(msg);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Message msg = new Message();
					msg.what = Values.NETWORK_ERROR;
					handler.sendMessage(msg);
					e.printStackTrace();
				}

			}

		}.start();
	}
	
	/**
	 * 静态handler,防止内存泄漏错误
	 * @author chris
	 *
	 */
	static class MyInnerHandler extends Handler {
        WeakReference<RegisterActivity> mActivity;

        MyInnerHandler(RegisterActivity mAct) {
        	mActivity = new WeakReference<RegisterActivity>(mAct);
        }

        @Override
        public void handleMessage(Message msg) {
            RegisterActivity theAct = mActivity.get();
            switch (msg.what) {
			case Values.FAIL_TO_REGISTER:
				Toast.makeText(theAct, "注册失败,"+ msg.obj.toString(), Toast.LENGTH_SHORT).show();
				break;
			case Values.SUCCESS_TO_REGISTER:
				Intent i = new Intent(theAct, MainActivity.class);
				i.putExtra("data", (Data)msg.obj);
				theAct.startActivityForResult(i, 0);
				break;
			case Values.NETWORK_ERROR:
				Toast.makeText(theAct, "网络连接错误", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
	    }
	 }
	 MyInnerHandler handler = new MyInnerHandler(this);

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		finish();
	}
}